﻿using System;
using DotNetNuke.UI;
using DotNetNuke.UI.ControlPanels;

namespace BrandonHaynes.Providers.ControlPanel
    {
    /// <summary>
    /// A control panel that loads an ASCX at runtime and includes the resulting
    /// instance in the control hierarchy.
    /// </summary>
    public class RuntimeControlPanel : NestedControlPanelBase
        {
        /// <summary>
        /// The key associated with the control panel metadata that identifies
        /// the ASCX path.
        /// </summary>
        private const string ControlPathKey = "path";

        protected override void OnInit(EventArgs e)
            {
            base.OnInit(e);
            Controls.Add(ControlPanel);
            }

        /// <summary>
        /// Loads the ASCX control panel instance associated with this control
        /// </summary>
        private ControlPanelBase ControlPanel
            {
            get
                {
                return ControlPanelPath != null
                           ? ControlUtilities.LoadControl<ControlPanelBase>(Page, ControlPanelPath)
                           : null;
                }
            }

        private string _controlPanelPath;
        /// <summary>
        /// Gets the path of the control panel associated with this instance
        /// </summary>
        private string ControlPanelPath
            {
            get
                {
                if (_controlPanelPath == null && Container != null)
                    Container.CurrentMapping.Attributes.TryGetValue(ControlPathKey, out _controlPanelPath);
                return _controlPanelPath;
                }
            }

        /// <summary>
        /// We expect that this control will be a direct child of the demutiplexing 
        /// control panel; here we obtain a reference to that instance.
        /// </summary>
        private Demultiplex Container
            { get { return Parent as Demultiplex; } }
        }
    }